package com.bah.tract.action;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import org.jboss.seam.annotations.In;
import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.PdfReportUtil;
import org.pentaho.reporting.libraries.resourceloader.Resource;
import org.pentaho.reporting.libraries.resourceloader.ResourceException;
import org.pentaho.reporting.libraries.resourceloader.ResourceManager;

public class ReportAction {
	@In
	private FacesContext facesContext;

	static {
		ClassicEngineBoot.getInstance().start();
	}

	protected void runReport(String reportLoc, Map<String, Object> params)
			throws IOException {
		final HttpServletResponse resp = (HttpServletResponse) facesContext
				.getExternalContext().getResponse();

		try {
			ResourceManager manager = new ResourceManager();
			manager.registerDefaults();
			URL reportUrl = getClass().getResource(reportLoc);
			Resource res = manager
					.createDirectly(reportUrl, MasterReport.class);
			MasterReport report = (MasterReport) res.getResource();
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				report.getParameterValues().put(entry.getKey(),
						entry.getValue());
			}
			PdfReportUtil.createPDF(report, resp.getOutputStream());
		} catch (ResourceException e) {
			throw new IOException(e);
		}

		facesContext.responseComplete();
	}

}
